package com.authine.cloudpivot.ext.utils.logistics;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.authine.cloudpivot.ext.constants.LogisticsConstant;
import com.authine.cloudpivot.ext.utils.HttpUtils;
import org.springframework.web.client.UnknownHttpStatusCodeException;

public class LogisticsUtils {

	static final String appCode= LogisticsConstant.APP_CODE;
	static final String appKey= LogisticsConstant.APP_KEY;
	static final String appSecret= LogisticsConstant.APP_SECRET;
	static final String host = "https://ali-deliver.showapi.com";

	public static Object queryLogistics(String companyCode,String waybillNum,String phone) {
		if(waybillNum==null || "".equals(waybillNum)) throw new RuntimeException("快递单号必填");
		
		if("shunfeng".equals(companyCode) && (phone==null || "".equals(phone))) {
			throw new RuntimeException("顺丰快递必须填写,收/寄件人手机号后四位");
		}

	    String path = "/showapi_expInfo";
	    String method = "GET";
	    Map<String, String> headers = new HashMap<String, String>();
	    //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
	    headers.put("Authorization", "APPCODE " + appCode);
	    Map<String, String> querys = new HashMap<String, String>();
	    if(companyCode==null || "".equals(companyCode)) {
	    	querys.put("com", "auto");
	    }else {
	    	querys.put("com", companyCode);
	    }
	    
	    querys.put("nu", waybillNum);
	    querys.put("phone", phone);

	    try {
	    	HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
	    	//获取response的body
	    	return JSON.parseObject(EntityUtils.toString(response.getEntity()));
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
		return null;
	}


	public static JSONObject getLogCode(String waybill) {
		if(waybill==null || "".equals(waybill)) throw new RuntimeException("快递单号必填");

		String path = "/fetchCom";
		String method = "GET";

		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Authorization", "APPCODE " + appCode);
		Map<String, String> querys = new HashMap<String, String>();
		querys.put("nu", waybill);

		try {
			HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
			return JSON.parseObject(EntityUtils.toString(response.getEntity()));
		} catch (UnknownHttpStatusCodeException ex) {
			ex.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


	public static void main(String[] args) {
		JSONObject o = (JSONObject)queryLogistics("shunfeng", "SF1405261088454", "18103843342");
		System.out.println(o.getJSONObject("showapi_res_body"));
	}
	
}
